#!/usr/bin/python
# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import web
import markdown
import json
import pymongo

conn = pymongo.Connection()    #连接mongoDB数据库
db = conn.gongjinshe
catalogs = db.catalogs         #保存文章的MongoDB文档

urls = (
    '/gongjinshe', 'gongjinshe',   #共进社主页
    '/blog/(.*)', 'blog',
    '/aboutme', 'aboutme',
    '/upload', 'upload',
    '/meet', 'meet',
    '/lsd/(.*)', 'leaguescience',
    '/list', 'listprocessor',       # 返回列表的json数据
    '/(.*)', 'index',
)

bloglist = [
    {
        'title': '迷',
        'url': '/blog/axin-mi'
    },
    {
        'title': '音乐流光',
        'url': '/blog/music-memory'
    },
    {
        'title': '老板的小王子',
        'url': '/blog/le_petit_prince'
    },
    {
        'title': '公司的编码规范',
        'url': '/blog/commet'
    },
    {
        'title': '安卓新手进阶',
        'url': '/blog/up-for-new-android'
    },
    {
        'title': '时间的故事',
        'url': '/blog/d-2014-8-21'
    },
    {
        'title': '给阿心写的排名代码',
        'url': '/blog/code-for-axin'
    },
]
PAGE_PATH = '/var/www/blog/pages/'
app = web.application(urls, globals())
render = web.template.render('/var/www/blog/template/')


def handler_mark_down(filename):
    context = ''
    try:
        fp = open(PAGE_PATH+filename)
        context = fp.read()
    except:
        pass
    if not context:
        return handler_mark_down('404.md')
    return context


class index:
    def GET(self, name):
        if name:
            text = handler_mark_down('404.md')
            html = markdown.markdown(text)
            return render.blog('404', html)
        return render.index(bloglist)


class blog:
    def GET(self, blogname):
        title = blogname
        text = handler_mark_down(blogname+'.md')
        html = markdown.markdown(text, ['prism_code'])
        return render.blog(title, html)


class aboutme:
    def GET(self):
        text = handler_mark_down('aboutme.md')
        html = markdown.markdown(text)
        return render.blog(u"一切关于阿南的", html)


class meet:
    def GET(self):
        text = handler_mark_down('meet.md')
        html = markdown.markdown(text)
        return render.blog(u"偶遇我？", html)


class upload:
    def GET(self):
        return u"使用post方法"

    def POST(self):
        file = web.input(upfile={})
        return file.upfile.file.read()


class gongjinshe:
    def GET(self):
        cataloglist = []
        for catalog in catalogs.find():
            cataloglist.append(catalog)
        return str(cataloglist)



class listprocessor:
    def GET(self):
        return json.dumps(bloglist)


class leaguescience:
    def GET(self, pagename):
        text = handler_mark_down(pagename+'.md')
        html = markdown.markdown(text, ['prism_code'])
        html = render.lsd(html)
        return html      # 直接返回markdown转换成的html数据，由客户端进行美化处理
    

application = app.wsgifunc()